package com.miyu.system.service.menu.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.miyu.common.utils.commonUtils.Comutils;
import com.miyu.system.dao.system.SysMenuDao;
import com.miyu.system.dao.system.SysSpaceDao;
import com.miyu.system.pojo.system.SysMenu;
import com.miyu.system.pojo.system.SysSpace;
import com.miyu.system.service.menu.SysMenuService;
import com.miyu.system.utils.enumeration.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 系统菜单服务impl
 *
 * @author longm
 * @date 2022/10/04
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Resource
    private SysMenuDao dao;

    @Resource
    private SysSpaceDao spaceDao;
    /**
     * 保存菜单
     *
     * @param params 参数个数
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject saveMenu(JSONObject params) {

        JSONObject rs = new JSONObject();
        SysMenu menu =  JSONObject.parseObject(params.toString(), SysMenu.class);
        if(StringUtils.isBlank(menu.getParentId())){
            menu.setParentId("-1");
        }else{
            //父级菜单不为空 更新父级菜单为非末级菜单
            SysMenu parent = dao.findById(menu.getParentId()).orElse(null);
            if(parent != null){
                parent.setIsLast("0");
            }
        }
        if(StringUtils.isBlank(menu.getMenuId())){
            String menuId = Comutils.getUUID();
            menu.setMenuId(menuId);
        }
        dao.save(menu);
        return Result.getInfoByCode("10001");
    }

    /**
     * 删除系统菜单
     *
     * @param params 参数个数
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject delSysMenu(JSONObject params) {
        JSONObject rs = new JSONObject();
        SysMenu menu =  JSONObject.parseObject(params.toString(),SysMenu.class);
        if(StringUtils.isNotBlank(menu.getMenuId())){
            dao.deleteById(menu.getMenuId());
            return Result.getInfoByCode("10001");
        }else {
            return Result.getInfoByCode("10002");
        }
    }

    /**
     * 查询菜单
     *
     * @param params 参数个数
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray queryMenu(JSONObject params) {
        String menuName = params.getString("menuName");
        return dao.queryMenu(menuName);
    }

    /**
     * 获取系统空间
     *
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray getSysSpace() {
        List<SysSpace> spaces = spaceDao.findAll();
        return JSONArray.of(spaceDao.findAll()).getJSONArray(0);
    }

    /**
     * 获取系统菜单通过角色
     *页面路由菜单
     * @param params 参数个数
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray getSysMenuByAuthority(JSONObject params) {
//        System.out.println(StpUtil.isLogin());
//        //登录用户数据
//        System.out.println(StpUtil.getExtra("userInfo"));
//        System.out.println(StpUtil.getPermissionList());
        //SysUser SysUser= JSONObject.parseObject(StpUtil.getTokenInfo().getTokenValue(),SysUser.class) ;
        //当前登录账户
       // System.out.println(SysUser);
        StringBuffer sql = new StringBuffer();
        sql.append("select");
        sql.append(" cm.menu_id,");
        sql.append(" cm.menu_component,");
        sql.append(" cm.menu_hidden,");
        sql.append(" cm.is_stop,");
        sql.append(" cm.is_sys,");
        sql.append(" cm.menu_mod,");
        sql.append(" cm.menu_name,");
        sql.append(" cm.menu_icon,");
        sql.append(" cm.path_all ,");
        sql.append(" cm.order_num,");
        sql.append(" cm.parent_id,");
        sql.append(" cm.space_id,");
        sql.append(" cm.space_id value,");
        sql.append(" cm.is_last,");
        sql.append(" cm.menu_name name ,");
        sql.append(" cs.space_zone ,");
        sql.append(" cs.space_name ");
        sql.append(" from  sys_menu cm "  );
        sql.append(" left join sys_space cs on cm.space_id = cs.space_id ");
        JSONArray menus = dao.queryJSONArrayBySql(sql.toString());
//        //递归获取菜单
        JSONArray menuTree = new JSONArray();
        menuTree = getRouterMenu(menuTree,menus);
        System.out.println(menuTree);
        return menuTree;
    }

    /**
     * 获取路由器菜单
     * @param menuTree 菜单树
     * @param menus    菜单
     * @return {@link JSONArray}
     */
    private JSONArray getRouterMenu(JSONArray menuTree, JSONArray menus) {
        for (int i = 0; i < menus.size(); i++) {
            JSONObject menu = menus.getJSONObject(i);
            if(menu.getString("parentId").equals("-1")){
                JSONArray rs = getRouterChildList(menu.getString("menuId"),menus);
                if(rs.size() > 0){
                    menu.put("children",rs);
                }
                JSONObject mate = new JSONObject();
                mate.put("title", menu.getString("menuName"));
                menu.put("mate",mate);
                menu.put("path",menu.getString("pathAll"));
                menuTree.add(menu);
            }
        }
        /*一级菜单排序*/
        menuTree.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
        return menuTree;
    }

    /**
     * 获取路由器孩子列表
     * 获取子菜单+排序
     * @param menuId 菜单id
     * @param menus  菜单
     * @return {@link JSONArray}
     */
    private JSONArray getRouterChildList(String menuId, JSONArray menus) {
        JSONArray rs = new JSONArray();
        for (int i = 0; i < menus.size(); i++) {
            JSONObject menu = menus.getJSONObject(i);
            if (menu.getString("parentId").equals(menuId)) {
                JSONArray menuList = getRouterChildList(menu.getString("menuId"),menus);
                if (menuList.size() > 0) {
                    menu.put("children",menuList);
                }
                JSONObject mate = new JSONObject();
                mate.put("title", menu.getString("menuName"));
                menu.put("mate",mate);
                menu.put("path",menu.getString("pathAll"));
                rs.add(menu);
                rs.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
            }
        }
        return rs;
    }

    /**
     * 查询系统菜单（菜单管理界面查询）
     *树状结构域
     *
     * @param param 参数
     * @return {@link JSONArray}
     */
    @Override
    public JSONArray querySysMenu(JSONObject param) {
        String menuName = "menuName";
        String spaceId = "spaceId";

        StringBuffer sql = new StringBuffer();
        sql.append("select");
        sql.append(" cm.menu_id,");
        sql.append(" cm.menu_component,");
        sql.append(" cm.menu_hidden,");
        sql.append(" cm.is_stop,");
        sql.append(" cm.is_sys,");
        sql.append(" cm.menu_mod,");
        sql.append(" cm.menu_name,");
        sql.append(" cm.menu_icon,");
        sql.append(" cm.path_all ,");
        sql.append(" cm.order_num,");
        sql.append(" cm.parent_id,");
        sql.append(" cm.space_id,");
        sql.append(" cm.menu_type,");
        sql.append(" cm.is_last,");
        sql.append("cm.menu_authority,");
        sql.append("cm.mome,");
        sql.append("cm.is_cache,");
        sql.append("cm.menu_param,");
        sql.append(" cs.space_zone ,");
        sql.append(" cs.space_name ");
        sql.append(" from  sys_menu cm "  );
        sql.append(" left join sys_space cs on cm.space_id = cs.space_id ");
        sql.append(" where 1=1 ");
        if(param.containsKey(menuName)&& StringUtils.isNotBlank(param.getString(menuName))){
            sql.append(" and cm.menu_name like '%").append(param.getString("menuName")).append("%'");

        }
        if(param.containsKey(spaceId)&& StringUtils.isNotBlank(param.getString(spaceId))){
            sql.append(" and cm.space_id = '").append(param.getString("spaceId")).append("'");
        }
        JSONArray menus = dao.queryJSONArrayBySql(sql.toString());
        JSONArray menuTree = new JSONArray();
         menuTree= getMenu(menuTree,menus);
        return menuTree;
    }

    /**
     * 获取树状菜单
     * @param menuTree 菜单树
     * @param menus    菜单
     * @return {@link JSONArray}
     */
    private JSONArray getMenu(JSONArray menuTree, JSONArray menus) {
        for (int i = 0; i < menus.size(); i++) {
            JSONObject menu = menus.getJSONObject(i);
            if(menu.getString("parentId").equals("-1")){
                JSONArray rs = getChildList(menu.getString("menuId"),menus);
                if(rs.size() > 0){
                    menu.put("children",rs);
                }
                menuTree.add(menu);
            }
        }
        /*一级菜单排序*/
        menuTree.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
        return menuTree;
    }

    /**
     * 获取子菜单+排序
     * @param menuId 菜单id
     * @param menus  菜单
     * @return {@link JSONArray}
     */
    private JSONArray getChildList(String menuId, JSONArray menus) {
        JSONArray rs = new JSONArray();
        for (int i = 0; i < menus.size(); i++) {
            JSONObject menu = menus.getJSONObject(i);
            if (menu.getString("parentId").equals(menuId)) {
                JSONArray menuList = getChildList(menu.getString("menuId"),menus);
                if (menuList.size() > 0) {
                    menu.put("children",menuList);
                }
                rs.add(menu);
                rs.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("orderNum")));
            }
        }
        return rs;
    }

}
